Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[Vue2]使用vuex在vue-cli webpack-simple專案自製語言系統

發表於 2017-08-24 更新於 2019-08-21 分類於 Vue2 , vuex

我的目的是希望做一個單獨的js檔案管理語言包,使所有的component都可以import使用

專案裡所需的東西

  1. vuex
  2. .json檔案做成的語言包
  3. 不要懷疑原來就是這麼精簡的心情

開始製作語言系統

我們先來製作兩個語言包吧!
首先創造兩個.json檔案分別為:
tw.json
en.json

tw.json
1
2
3
{
language: '中文'
}
en.json
1
2
3
{
language: 'English'
}

再來創造一個專門管理語言的js檔案,我命名為config:

config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

var config = new Vuex.Store({
state: {
language: 'tw',
translations: {}
},
mutations: {
getTranslations () {
if ( state.language === 'tw' ) {
$.ajax({
url:'./tw.json',
type: 'get',
async: false,//設定同步讓語言包一定要先取到才export出去
success: function (response) {
state.translations = response;
state.language === 'en'
}
});
} else {
$.ajax({
url: './en.json',
type: 'get',
async: false,
success: function (response) {
state.translations = response;
state.language === 'tw'
}
});
}
}
}
});

之後開始創造html:
P.S:這裡用最兩光的按鈕直接切換語系,正常來講是下拉式選單之類的才最適合。

index.html
1
2
3
4
5
<center id="showTranslations" v-cloak>
<button @click="changeLanguage">change</button>
現在語系:{{ translations.language }}
</center>
<div id="component"></div>

開始撰寫main.js

main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import Vue from 'vue'
import Vuex from 'vuex'
import config from './config.js'

import myComponent from './component.vue'

Vue.use(Vuex)

//把從.vue檔案import的component實作出來
new Vue({
el: '#component',
render: h => h(myComponent)
})

//主要的東西也可以直接寫在此js裡面
new Vue({
el: '#showTranslations',
data: function () {
return {
someData: ''
}
},
methods: {
changeLanguage: function () {
config.commit('getTranslations');
//要呼叫vuex的function要使用commit
}
},
computed: {
translation() {
return config.state.translations;
//只用這種方法去讀取語言包!
}
}
})

開始撰寫component.vue

component.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<center>
component語系:{{ translations.language }}
</center>
</template>

<script>
import Vue from 'vue'
import Vuex from 'vuex'

import config from './config.js'
//每個component都要引進語言包!
Vue.use(Vuex)
export default {
data() {
return {
someData: ''
}
},
computed: {
translation() {
return config.state.translations;
}
}
}
</script>

這樣就可以簡單模擬一個專案有一隻js檔案是使用vuex達到讓每個component運用裡面的資料做很多初始化的事情囉!

執得注意的地方:
config的ajax一定要使用同步執行完整才export出去(async: false),promise,axios等等都沒辦法做到。

這個方法有個比較大的缺點是json擋就得很土炮的自己一個一個字打上去囉!

# Vue2 # vuex # vue-cli # webpack-simple
[JavaScript]fadeIn & fadeOut with inline-block
[Vue2]iis伺服器引擎設定vue-router
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. 專案裡所需的東西
  2. 2. 開始製作語言系統
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0